<?php
namespace Home\Controller;
use Cart\Cart;
use Cart\Storage\SessionStore;
use Common\Controller\BaseController;

class PublicController extends BaseController {

	protected $cart; //购物车
	protected $cart_array; //购物车数组

	public function _initialize() {
		parent::_initialize();
		$id = 'cart-007';
		$cartSessionStore = new SessionStore();
		$this->cart = new Cart($id, $cartSessionStore);
		if ($_SESSION['cart-007']) {
			$this->cart->restore();
		} else {
			$this->cart->save();
		}
		$this->cart_array['cart_arr'] = $this->cart->toArray();
		$this->cart_array['cart_items'] = $this->cart->totalItems();
		$this->cart_array['cart_amount'] = $this->cart->total();
		//dump($this->cart_array);
		$this->assign("shopcart", $this->cart_array);
	}

	//根据国家代码返回州
	public function getState() {
		I("iso") == 3 ? $iso = 3 : $iso = 2;
		$this->ajaxReturn(parent::getState(I("country_name"), $iso));
	}

	/**
	 * 登录界面
	 */
	public function login() {
		if (session("cid")) {
			$redirect = session("login_redirect");
			session("login_redirect", null);
			if ($redirect) {
				$this->redirect($redirect);
			} else {
				$this->redirect("Customer/index");
			}
		} else {
			$this->display();
		}
	}

	/**
	 * 添加购物车之前的判断
	 */
	protected function beforeAddCart($pid, $quantity) {
		$oop = D("ProductView");
		$con['product_id'] = $pid;
		$con['product_status'] = 1;
		$con['cat_status'] = 1;
		$con['product_quantity'] = array("gt", $quantity);
		$list = $oop->where($con)->find();
		if ($list && $quantity > 0) {
			return $list;
		} else {
			return false;
		}
	}

	//登录操作
	public function checkin() {
		if ($this->web_config['web_verify_code']) {
			$this->checkCode();
		}
		$oop = M('customer');
		$map['cs_email'] = I('username');
		$map['cs_status'] = 1;
		$authInfo = $oop->where($map)->find();

		//使用用户名、密码和状态的方式进行认证
		if (!$authInfo || $authInfo['cs_pwd'] != md5(I('password'))) {
			$this->error(L("error_pwd"));
		}

		session("cid", $authInfo['cs_id']);
		//dump($_SESSION);exit;
		$this->success(L("checkin_success"));
	}

	//登出
	public function logout() {
		session("cid", null);
		$this->success("Logout successfully.", U("Index/index"));
	}
	//注册
	public function register() {
		if (I("cs_pwd") != I("confirm_pwd")) {
			$this->error("Password doesn't match twice");
		}
		try {
			$oop = M("customer");
			$oop->create();
			$oop->cs_pwd = md5(I("cs_pwd"));
			$oop->cs_ip = get_client_ip();
			if ($cid = $oop->add()) {
				session("cid", $cid);
				$this->success("Registered successfully!");
			} else {
				$this->error("Error,please try again.");
			}

		} catch (\Exception $e) {
			if ($e->getCode() == 23000) {
				$this->error("Acount exists...");
			}
		}
	}

}